<?php

namespace app\api\model;

use app\api\model\ConfigSystem as Config;
use app\api\model\VolleyDesc as Balance;
use app\api\model\MallDistribution;
use app\api\model\MallOrderFanli;
use app\service\UserRepeat;
use GatewayClient\Gateway;
use think\Db;
use think\Log;

class OrderCommon extends Common {
    /**
     * @param $out_trade_no
     * @param $orders
     * @return mixed
     */
    static public function notify($out_trade_no, $orders = '') {
        $state = 0;
        $user_id = 0;

        // 启动事务
        Db::startTrans();
        try {
            $mark = substr($out_trade_no, 0, 2);
            switch ($mark) {
            case 'se':
                # 服务订单
                //$data = Db::name('order_of_service')->master()->where(['number' => $out_trade_no, 'paystate' => 0])->lock(true)->find();
                $data = Db::name('order_of_service')->master()->where(['number' => $out_trade_no, 'paystate' => 0])->find();
                if ($data) {
                    $user_id = $data['user_id'];
                    Db::name('order_of_service')->where(['id' => $data['id']])->update(['paystate' => 1, 'update_time' => time()]);

                    $state = 1;
                    Db::name('platform_balance')->insert(['types' => 2, 'money' => $data['price'], 'content' => '用户(ID:' . $data['user_id'] . ')购买服务', 'create_time' => time()]);
                    $order_data = json_decode($data['data'], true);
                    // 添加免费聊天。
                    // 线上聊天无开始时间，服务主发首条消息则作为开始时间，并计算结束时间
                    // 线下聊天立即开始，无结束时间，结束时间由服务结束结算后生成
                    Db::name('privatechat_free')->insert([
                        'user_id'     => $data['user_id'] > $data['shopowner'] ? $data['shopowner'] : $data['user_id'],
                        'another_id'  => $data['user_id'] > $data['shopowner'] ? $data['user_id'] : $data['shopowner'],
                        'server'      => $data['shopowner'],
                        'order_sn'    => $data['number'],
                        'create_time' => time(),
                        'start_time'  => $data['type'] == 1 ? time() : 0,
                        'end_time'    => $data['type'] == 1 ? 0 : time() + 3600 * $data['num'],
                        'method'      => $order_data['method']
                    ]);

                }
                break;
            case 'rd':
                # 地点红包
                //$data = Db::name('user_address_red_packet')->master()->where(['number' => $out_trade_no, 'paystate' => 0])->lock(true)->find();
                $data = Db::name('user_address_red_packet')->master()->where(['number' => $out_trade_no, 'paystate' => 0])->find();
                if ($data) {
                    $user_id = $data['user_id'];
                    Db::name('user_address_red_packet')->where(['id' => $data['id']])->update(['paystate' => 1, 'pay_time' => time()]);

                    $state = 1;
                    Db::name('platform_balance')->insert(['types' => 2, 'money' => $data['totalprice'], 'content' => '用户(ID:' . $data['user_id'] . ')发放地点红包', 'create_time' => time()]);
                }
                break;
            case 'ag':
                # 地点团购
                //$data = Db::name('order_of_addressgood')->master()->where(['number' => $out_trade_no, 'paystate' => 0])->lock(true)->find();
                $data = Db::name('order_of_addressgood')->master()->where(['number' => $out_trade_no, 'paystate' => 0])->find();
                if ($data) {
                    $user_id = $data['user_id'];
                    Db::name('order_of_addressgood')->where(['id' => $data['id']])->update(['paystate' => 1, 'pay_time' => time()]);

                    $state = 1;
                    Db::name('platform_balance')->insert(['types' => 2, 'money' => $data['price'], 'content' => '用户(ID:' . $data['user_id'] . ')购买团购商品', 'create_time' => time()]);
                }
                break;
            case 'aj':
                # 邀约活动
                //$data = Db::name('activity_join')->master()->where(['number' => $out_trade_no, 'paystate' => 0])->lock(true)->find();
                $data = Db::name('activity_join')->master()->where(['number' => $out_trade_no, 'paystate' => 0])->find();
                if ($data) {
                    $user_id = $data['user_id'];
                    Db::name('activity_join')->where(['id' => $data['id']])->update(['paystate' => 1, 'pay_time' => time()]);

                    Db::name('activity_offline')->where(['id' => $data['active_id']])->setInc('joins');

                    $state = 1;
                    Db::name('platform_balance')->insert(['types' => 2, 'money' => $data['price'], 'content' => '用户(ID:' . $data['user_id'] . ')报名邀约活动', 'create_time' => time()]);
                }
                break;
            case 'fl':
                # Flag
                //$data = Db::name('user_flag')->master()->where(['number' => $out_trade_no, 'paystate' => 0])->lock(true)->find();
                $data = Db::name('user_flag')->master()->where(['number' => $out_trade_no, 'paystate' => 0])->find();
                if ($data) {
                    $user_id = $data['user_id'];
                    $timenow = time();
                    Db::name('user_flag')->where(['id' => $data['id']])->update(['paystate' => 1, 'update_time' => time()]);
                    $user = Db::name('user')->find($data['user_id']);
                    Db::name('flags')->insertGetId([
                        'user_id'     => $user['id'],
                        'flag_id'     => $data['id'],
                        'content'     => '我创建了一个Flag，快来围观吧~',
                        'day'         => 0,
                        'images'      => '',
                        'longitude'   => $user['longitude'],
                        'latitude'    => $user['latitude'],
                        'create_time' => $timenow,
                        'city'        => $user['city'],
                    ]);

                    $state = 1;

                    if ($data['limit_uid']) {
                        Privatechat::tip($data['user_id'], $data['limit_uid'], "邀请你监督我完成小目标【" . $data['content'] . "】", json_encode(['id'=>$data['id'], 'content'=>$data['content']], JSON_UNESCAPED_UNICODE), 1, -2);
                    }
                    Db::name('platform_balance')->insert(['types' => 2, 'money' => $data['price'], 'content' => '用户(ID:' . $data['user_id'] . ')创建Flag支付激励金', 'create_time' => time()]);
                }
                break;

            default:
                # 充值
                //$data = (new Topup)->master()->where(['numbers' => $out_trade_no, 'state' => 0])->lock(true)->find();
                $data = (new Topup)->master()->where(['numbers' => $out_trade_no, 'state' => 0])->find();
                if ($data) {
                    $user = User::get($data['fk_userid']);
                    if ($user['sex'] == '女') {
                        Balance::beans($data->fk_userid, $data->money, '充值', 1);
                    } else {
                        Balance::index($data->fk_userid, $data->money, '充值', 1);
                    }

                    $user_id = $data->fk_userid;
                    // 用户业绩统计
                    UserData::createData($data['fk_userid'], $data['price'], 'topup');
                    UserData::createData($data['fk_userid'], $data['money'], 'topup_volley');

                    $updates = ['id' => $data->id, 'state' => 1, 'addtime' => date('Y-m-d H:i:s'), 'sys_channel'=>getenv('APP_CHANNEL')];

                    if ($orders) {
                        $updates['data'] = json_encode($orders);
                        $updates['type'] = isset($orders['buyer_id']) || (isset($orders['pay_channel']) && $orders['pay_channel'] == 'alipay') ? 1 : 0;
                    }
                    Topup::update($updates);

                    $config = Config::index('', 'topup_reward');


                    // 抽奖机会+1
                    if ($user && intval($config['topup_reward']) && $user['lottery_count'] == 0 && $user['topup_reward'] < $config['topup_reward']) {
                        User::where(['id' => $data['fk_userid']])->update([
                            'lottery_count' => $user['lottery_count'] + 1,
                            'topup_reward'  => $user['topup_reward'] + 1,
                        ]);
                    }

                    $topupSelect = TopupSelect::get($data['sid']);

                    if ($topupSelect) {
                        //$result = Topup::where(['id' => ['neq', $data->id], 'fk_userid' => $data->fk_userid, 'state' => 1]);
                        //if (!$result) {
                        if ($topupSelect->reward_money + 0) {
                            Balance::index($data->fk_userid, $topupSelect->reward_money, '充值赠送', 1);
                        }

                        if ($topupSelect->reward_noble && $topupSelect->reward_noble_day + 0) {
                            $gradeNoble = GradeNoble::get($topupSelect->reward_noble);

                            if ($gradeNoble) {
                                //$user = User::get($data->fk_userid);

                                $where = ['id' => $data->fk_userid];
                                if ($user['noble_time'] <= time()) {
                                    $where['noble_grade'] = $gradeNoble['grade'];
                                }

                                $where['noble_time'] = time() + $topupSelect->reward_noble_day * 86400;

                                User::update($where);
                            }
                        }

                        if ($topupSelect->reward_car && $topupSelect->reward_car_day + 0) {
                            $car = Car::get($topupSelect->reward_car);

                            if ($car) {
                                $userCar = UserCar::get(['car_id' => $topupSelect->reward_car, 'user_id' => $data->fk_userid]);

                                $current_time = time();

                                if ($userCar) {
                                    $expire = $userCar['expire'] > $current_time ? $userCar['expire'] : $current_time;
                                    $expire += $topupSelect->reward_car_day * 86400;

                                    UserCar::update(['id' => $userCar->id, 'expire' => $expire, 'update_time' => time()]);
                                } else {
                                    UserCar::create([
                                        'car_id'      => $topupSelect->reward_car,
                                        'user_id'     => $data->fk_userid,
                                        'expire'      => $current_time + $topupSelect->reward_car_day * 86400,
                                        'create_time' => $current_time,
                                        'update_time' => $current_time,
                                    ]);
                                }
                            }
                        }
                        //}
                    }

                    $parent = User::where(['yqm' => $user['yqr']])->find();

                    /*if ($parent && $parent['proxy']) {
                    User::fencheng($data->fk_userid, 0, $data->price * 10, 'topup');
                    } else {
                    User::reward($data->fk_userid, $data->price * 10, '充值');
                    }*/

                    if ($parent && $user['sex'] == '男') {
                        $fmoney = $data->money;
                        // if ($data->price >= 50) {
                        //     $fmoney -= getenv('APP_RATE') * 10;
                        // } else if ($data->price >= 15) {
                        //     $fmoney -= getenv('APP_RATE') * 5;
                        // }
                            User::reward($data->fk_userid, $fmoney, $user['name'] . '(' . $data->fk_userid . ') 充值', 'topup');
                    }

                    $state = 1;

                    Db::name('platform_balance')->insert(['types' => 2, 'money' => $data->price, 'content' => '用户(ID:' . $data->fk_userid . ')充值', 'create_time' => time()]);
                    if ($orders && is_array($orders) && isset($orders['expend']) && isset($orders['expend']['cashPayAmt'])) {
                        try{
                            Db::name('order_info')->insert(['number'=>$out_trade_no, 'money'=>$data->price, 'data'=>$orders?json_encode($orders):'', 'create_time'=>time(),'remain_amount'=>$data->price]);
                        } catch (\think\db\exception\PDOException $e) {
                            // 忽略唯一约束冲突（错误码23000）
                            if ($e->getCode() !== '23000') {
                                Log::error("订单{$out_trade_no}-".date('Y-m-d H:i:s')."插入失败: {$e->getMessage()}");
                                throw $e; // 其他错误继续抛出
                            }
                        }
                    }

                    // $topupcount = Db::name('topup')->where('type!=3 and state=1 and fk_userid='.$data->fk_userid)->sum('price');
                    // if($topupcount >= 5000){
                    //     Privatechat::notice($data->fk_userid, '平台不存在送礼物解锁联系方式以及解锁免费聊天权限的功能，请你知悉。', '');
                    // }

                }

                # 付费订单
                if (!$state) {
                    //$data = (new OrderCommon)->master()->where(['number' => $out_trade_no, 'status' => 0])->lock(true)->find();
                    $data = (new OrderCommon)->master()->where(['number' => $out_trade_no, 'status' => 0])->find();
                    if ($data) {
                        $user_id = $data->user_id;
                        if ($data->types == 1) {
                            # 现金红包

                            $chat_id = json_decode($data->data['data'], true)['id']; # 聊天信息id

                            $chat = Privatechat::get($chat_id);

                            if ($chat && in_array($chat['type'], [5, 7]) && $chat->status == -1) {

                                Privatechat::update(['id' => $chat_id, 'status' => 0]);

                                $url = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['HTTP_HOST'] . $_SERVER['SCRIPT_NAME'] . '/apis/index.php/home/privatechat/';
                                $url = str_replace('/index.php/apis', '/apis', $url);

                                curl($url . 'getNewMsg', json_encode(['userid' => $chat->touserid, 'touserid' => $chat->userid]), 0);
                                curl($url . 'getNewMsg', json_encode(['userid' => $chat->userid, 'touserid' => $chat->touserid]), 0);
                                curl($url . 'getOtherList', json_encode(['userid' => $chat->touserid, 'count' => '', 'type' => '']), 0);
                            }
                        } elseif ($data->types == 5) {
                            $datas = json_decode($data['data'], true);

                            $userCar = UserCar::get(['car_id' => $datas['id'], 'user_id' => $data['user_id']]);

                            $time = [1, 3, 12];

                            if ($userCar) {
                                $expire = $userCar['expire'] > time() ? $userCar['expire'] : time();
                                $expire = $expire + $time[$datas['expire']] * 86400;

                                UserCar::update(['id' => $userCar['id'], 'expire' => $expire, 'update_time' => time()]);
                            } else {
                                $expire = time() + $time[$datas['expire']] * 86400;

                                UserCar::create(['car_id' => $datas['id'], 'user_id' => $data['user_id'], 'expire' => $expire, 'create_time' => time(), 'update_time' => time()]);
                            }
                        } elseif ($data->types == 6) {
                            $datas = json_decode($data['data'], true);


                            if ($orders) {
                                $datas['pay_data'] = json_encode($orders);
                                $updates['data'] = json_encode($datas, JSON_UNESCAPED_UNICODE);
                                $updates['pays'] = isset($orders['buyer_id']) || (isset($orders['pay_channel']) && $orders['pay_channel'] == 'alipay') ? 2 : 3;
                            }

                            $gradeNobleTimes = GradeNobleTimes::get($datas['id']);
                            $gradeNoble      = GradeNoble::get($gradeNobleTimes->noble_id);

                            $user = User::get($data['user_id']);

                            $time = $user['noble_time'] > time() ? $user['noble_time'] : time();
                            $time = strtotime($gradeNobleTimes->keep . ' ' . $gradeNobleTimes->times, $time);

                            if ($gradeNobleTimes->reward + 0) {
                                Balance::index($data['user_id'], $gradeNobleTimes->reward, '充值VIP赠送', 1);
                            }

                            $userGrade = UserNoble::get(['user_id' => $data['user_id'], 'grade' => $gradeNoble->grade]);
                            if ($userGrade) {
                                $userNobleTime = $userGrade['expire'] > time() ? $userGrade['expire'] : time();
                                $userNobleTime = strtotime($gradeNobleTimes->keep . ' ' . $gradeNobleTimes->times, $userNobleTime);

                                UserNoble::update(['id' => $userGrade->id, 'expire' => $userNobleTime, 'update_time' => time()]);
                            } else {
                                $userNobleTime = strtotime($gradeNobleTimes->keep . ' ' . $gradeNobleTimes->times);
                                UserNoble::create([
                                    'user_id'     => $data['user_id'],
                                    'grade'       => $gradeNoble->grade,
                                    'expire'      => $userNobleTime,
                                    'create_time' => time(),
                                    'update_time' => time(),
                                ]);
                            }

                            User::update(['id' => $data['user_id'], 'noble_grade' => $gradeNoble->grade, 'noble_time' => $time]);

                            User::fencheng($data['user_id'], 0, $data['money'] * getenv('APP_RATE'), 'vip');

                            /*if ($user['yqr']) {
                            $parent = User::where(['yqm' => $user['yqr']])->find();

                            if ($parent && $parent['proxy']) {
                            User::fencheng($data['user_id'], 0, $data['money'] * 10, 'vip');
                            } else {
                            User::reward($data['user_id'], $data['money'], '充值VIP');
                            }
                            }*/

                            GradeNobleUse::where(['user_id' => $data['user_id'], 'create_time' => ['egt', strtotime(date('Ymd'))]])->delete();
                            // User::rewardHunjie($user_id, $data['money'] * getenv('APP_RATE'), 'vip_shouyi_', '开通会员', $out_trade_no);
                            
                        } elseif ($data->types == 8) {
                            $datas = json_decode($data['data'], true);

                            $vip_style = Db::name('hunjie_vip_style')->where(['id'=>$datas['id']])->find();

                            $user = Db::name('user_profile')->where(['user_id'=>$data['user_id']])->find();

                            $state = 0;
                            $expire_time = 0;
                            if (strtotime($user['pull_line']) < time()) {
                                $state = 1;
                                $expire_time = strtotime("+ " . $vip_style['day'] . " day");
                            } else {
                                $expire_time = strtotime($user['pull_line']) + $vip_style['day'] * 86400;
                            }
                            $pull_line = date('Y-m-d H:i:s', $expire_time);
                            Db::name('user_profile')->where(['user_id'=>$data['user_id']])->update(['pull_line'=>$pull_line, 'pull_line_count'=>$user['pull_line_count']+$vip_style['assists']]);
                            
                            Db::name('hunjie_vip_order')->insert([
                                'number'=>$out_trade_no,
                                'user_id'=>$data['user_id'],
                                'price'=>$data['money'],
                                'day'=>$vip_style['day'],
                                'time'=>time(),
                                'expire_time'=>$expire_time,
                                'state'=>$state,
                                'assists'=>$vip_style['assists']
                            ]);
                            User::rewardHunjie($user_id, $data['money'] * getenv('APP_RATE'), 'pullline_shouyi_', '开通牵线VIP', $out_trade_no);

                        } elseif ($data->types == 9) {
                            $datas = json_decode($data['data'], true);
                            Db::name('user_profile')->where(['user_id'=>$user_id])->update(['proxy'=>1]);

                            $datas['user_id'] = $user_id;
                            $datas['state'] = 1;
                            Db::name('hunjie_proxy')->insert($datas);

                            User::rewardHunjie($user_id, $data['money'] * getenv('APP_RATE'), 'matchmaking_shouyi_', '开通婚介', $out_trade_no);

                        } elseif ($data->types == 10) {
                            $datas = json_decode($data['data'], true);

                            Db::name('hunjie_partner_apply')->insert(['user_id'=>$user_id, 'type'=>$datas['type'], 'area'=>$datas['area'], 'create_time'=>strtotime($data['create_time']), 'update_time'=>time()]);
                        }

                        $updates = ['id' => $data->id, 'status' => 1, 'update_time' => time()];
                        $updates['pays'] = isset($orders['buyer_id']) ? 2 : 3;
                        self::update($updates);

                        $state = 1;

                        $contain = ['5' => '座驾', '6' => 'VIP', '8' => '人工牵线VIP', '9' => '婚介', '10' => '婚介合伙人'];

                        if ($orders && is_array($orders) && isset($orders['expend']) && isset($orders['expend']['cashPayAmt'])) {
                            try{
                                Db::name('order_info')->insert(['number'=>$out_trade_no, 'money'=>$data->money, 'data'=>$orders?json_encode($orders):'', 'create_time'=>time(),'remain_amount'=>$data->money]);
                            } catch (\think\db\exception\PDOException $e) {
                                // 忽略唯一约束冲突（错误码23000）
                                if ($e->getCode() !== '23000') {
                                    Log::error("订单{$out_trade_no}-".date('Y-m-d H:i:s')."插入失败: {$e->getMessage()}");
                                    throw $e; // 其他错误继续抛出
                                }
                            }
                        }
                        Db::name('platform_balance')->insert(['types' => 2, 'money' => $data['money'], 'content' => '用户(ID:' . $data['user_id'] . ')购买' . $contain[$data['types']], 'create_time' => time()]);
                    }
                }

                # 商店订单
                if (!$state) {
                    $db = Db::connect(getenv('APP_MALL_DATABASE'));
                    //$data = $db->name('mall_order')->master()->where(['number' => $out_trade_no, 'status' => 0])->lock(true)->find();
                    $data = $db->name('mall_order')->master()->where(['number' => $out_trade_no, 'status' => 0])->find();
                    if ($data) {
                        $user_id = $data['uid'];
                        $uid = $data['uid']?:0;
                        $to_user = $data['to_user']?:0;

                        if (getenv('APP_MALL_DATABASE')!='database') {
                            $user_channel_profiles = $db->name('user_channel_profile')->where(['user_id'=>['in',[$uid, $to_user]], 'sys_channel'=>getenv('APP_CHANNEL')])->column('*','user_id');
                            if ($user_channel_profiles) {
                                $uid_r = $user_id = $user_channel_profiles[$uid]['source_uid']??$uid;
                                $to_user_r = $user_channel_profiles[$to_user]['source_uid']??$to_user;
                            }
                        }

                        $db->name('mall_order')->where(['id' => $data['id']])->update(['status' => 1, 'charge_time' => time()]);
                        MallDistribution::Add($data['id']);
                        MallOrderFanli::Add($data['id']);

                        $state = 1;
                        $updates = [];
                        
                        $option = '购买商品';
                        if ($orders) {
                            $updates['paymethod'] = isset($orders['buyer_id']) ? 1 : 2;
                            $updates['gateway'] = isset($orders['buyer_id']) ? 2 : 3;
                        }
                        if ($data['types'] == 2) {
                            $request = request();
                            $url = $request->domain() . str_replace('/index.php', '', $request->baseFile()) . '/apis/home/privatechat/addtalk';

                            $order_id = $data['id'];

                            $mallItem = $db->name('mall_order_item')->where(['order_id'=>$data['id']])->select();
                            $goods = [];
                            $goodsnum = 0;
                            foreach ($mallItem as $mkey => $mvalue) {
                                $mallRecords = $db->name('mall_records')->where(['user_id' => $uid, 'to_user' => $to_user, 'goods_id' => $mvalue['goods_id']])->find();
                                if ($mallRecords) {
                                    $db->name('mall_records')->where(['id' => $mallRecords['id']])->setInc('num', $mvalue['num']);
                                } else {
                                    $db->name('mall_records')->insert(['user_id' => $uid, 'to_user' => $to_user, 'goods_id' => $mvalue['goods_id'], 'num' => $mvalue['num'], 'create_time' => time(), 'update_time' => time()]);
                                }
                                if (empty($goods)) {
                                    $goods = $db->name('mall_goods')->find($mvalue['goods_id']);
                                }
                                $goodsnum += $mvalue['num'];
                            }

                            $datas = [
                                'userid' => $uid_r,
                                'touserid' => $to_user_r,
                                'type' => 18,
                                'content' => '[礼物]',
                                'data' => json_encode(['order_id' => $order_id, 'name' => $goods['name'] . ($goodsnum > 1 ?" 等多件商品":""), 'image' => $goods['image'], 'num' => $goodsnum, 'money' => $data['total']], JSON_UNESCAPED_UNICODE)
                            ];
                            
                            curl($url, json_encode($datas, JSON_UNESCAPED_UNICODE));
                        } else if ($data['types'] == 1){
                            if ($orders && isset($orders['other_data']) && isset($orders['other_data']['uid'])) {
                                $uid = $orders['other_data']['uid'];
                                if ($uid != $data['uid']) {
                                    $option = '代付商品';
                                }
                            } else if ($data['to_user'] && $data['to_user'] != $data['uid']) {
                                $uid = $data['to_user'];
                                $option = '代付商品';
                            }
                            if ($option == '代付' || $data['to_user'] != $uid) {
                                $updates['to_user'] = $uid;
                            }
                            $uid = $user_channel_profiles[$uid]['source_uid']??$uid;
                        }
                        if (sizeof($updates)) {
                            $db->name('mall_order')->where(['id' => $data['id']])->update($updates);
                        }
                        Db::name('platform_balance')->insert(['types' => 2, 'money' => $data['money'], 'content' => '用户(ID:' . $uid . ')'.$option, 'create_time' => time()]);
                    }
                }
                break;
            }


            // 提交事务
            Db::commit();
            // 非主要数据的操作放在后续
            switch ($mark) {
                case 'se':
                    Gateway::sendToUid(getenv('SOCKET_PREFIX') . $data['user_id'], json_encode(['code' => 200, 'v' => 1, 'action' => 'api/privatechat/detail', 'data' => $data['shopowner']]));
                    Gateway::sendToUid(getenv('SOCKET_PREFIX') . $data['shopowner'], json_encode(['code' => 200, 'v' => 1, 'action' => 'api/privatechat/detail', 'data' => $data['user_id']]));
                    Gateway::sendToUid(getenv('SOCKET_PREFIX') . $data['shopowner'], json_encode(['code' => 200, 'v' => 1, 'action' => 'api/order/orderCount']));
                    
                    $userphone = Db::name('user')->where(['id' => $data['shopowner']])->value('phone');
                    Privatechat::tip($data['user_id'], $data['shopowner'], "对方购买了你发布的服务【" . $data['title'] . "】", json_encode($data, JSON_UNESCAPED_UNICODE), 1, -1);

                    (new Juhe)->sendTpl($userphone, '250348');
                    break;
                default:
                    break;
            }
        } catch (\Exception $e) {
            Log::write($e->getMessage(), 'error');
            // 回滚事务
            Db::rollback();
        }

        if ($orders && $user_id) {
            $payid = isset($orders['openid']) ? $orders['openid'] : (isset($orders['buyer_id']) ? $orders['buyer_id'] : '');
            UserRepeat::InsertS($user_id, 'pay_ids', $payid);
        }
        return $state;
    }

    /**
     * @param $types
     * @param $user_id
     * @param $money
     * @param $method
     * @param $data
     * @param $status
     */
    static public function index($types, $user_id, $money, $method, $data = '', $status = 0) {
        $type = ['8'=>'hv', '9'=>'hj', '10'=>'hh'];
        $order_sn     = uniqid($type[$types]??'');
        $current_time = time();

        $data = [
            'types'       => $types,
            'number'      => $order_sn,
            'user_id'     => $user_id,
            'money'       => $money,
            'pays'        => $method,
            'data'        => $data,
            'status'      => $status,
            'create_time' => $current_time,
            'update_time' => $current_time,
        ];

        $order = self::create($data);

        return ['id' => $order->id, 'order_sn' => $order_sn];
    }
}
